<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/limh/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/limh/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/limh/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/limh/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/limh/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/limh/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/limh/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="教程,">










<meta name="description" content="给从机下发不同的指令，从机去执行不同的操作，这个就是判断一下功能码即可，和我们前边学的实用串口例程是类似的。多机通信，无非就是添加了一个设备地址判断而已，难度也不大。我们找了一个 Modbus 调试精灵，通过设置设备地址，读写寄存器的地址以及数值数量等参数，可以直接替代串口调试助手，比较方便的下发多个字节的数据，如图 18-7 所示。我们先来就图中的设置和数据来对 Modbus 做进一步的分析，图">
<meta name="keywords" content="教程">
<meta property="og:type" content="article">
<meta property="og:title" content="18.3、Modbus多机通信程序">
<meta property="og:url" content="https://tdnr.gitee.io/limh/2014/12/01/mcu119/index.html">
<meta property="og:site_name" content="土逗牛肉">
<meta property="og:description" content="给从机下发不同的指令，从机去执行不同的操作，这个就是判断一下功能码即可，和我们前边学的实用串口例程是类似的。多机通信，无非就是添加了一个设备地址判断而已，难度也不大。我们找了一个 Modbus 调试精灵，通过设置设备地址，读写寄存器的地址以及数值数量等参数，可以直接替代串口调试助手，比较方便的下发多个字节的数据，如图 18-7 所示。我们先来就图中的设置和数据来对 Modbus 做进一步的分析，图">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250K25I27.png">
<meta property="og:updated_time" content="2019-01-31T13:14:53.374Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="18.3、Modbus多机通信程序">
<meta name="twitter:description" content="给从机下发不同的指令，从机去执行不同的操作，这个就是判断一下功能码即可，和我们前边学的实用串口例程是类似的。多机通信，无非就是添加了一个设备地址判断而已，难度也不大。我们找了一个 Modbus 调试精灵，通过设置设备地址，读写寄存器的地址以及数值数量等参数，可以直接替代串口调试助手，比较方便的下发多个字节的数据，如图 18-7 所示。我们先来就图中的设置和数据来对 Modbus 做进一步的分析，图">
<meta name="twitter:image" content="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250K25I27.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/limh/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tdnr.gitee.io/limh/2014/12/01/mcu119/">





  <title>18.3、Modbus多机通信程序 | 土逗牛肉</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans ">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/limh/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">土逗牛肉</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/limh/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/limh/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/limh/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/limh/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/limh/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tdnr.gitee.io/limh/limh/2014/12/01/mcu119/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="土逗牛肉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/limh/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="土逗牛肉">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">18.3、Modbus多机通信程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2014-12-01T20:41:19+08:00">
                2014-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/limh/categories/单片机教程/" itemprop="url" rel="index">
                    <span itemprop="name">单片机教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>给从机下发不同的指令，从机去执行不同的操作，这个就是判断一下功能码即可，和我们前边学的实用串口例程是类似的。多机通信，无非就是添加了一个设备地址判断而已，难度也不大。我们找了一个 Modbus 调试精灵，通过设置设备地址，读写寄存器的地址以及数值数量等参数，可以直接替代串口调试助手，比较方便的下发多个字节的数据，如图 18-7 所示。我们先来就图中的设置和数据来对 Modbus 做进一步的分析，图中的数据来自于调试精灵与我们接下来要讲的例程之间的交互。</p>
<p><img src="http://c.biancheng.net/cpp/uploads/allimg/140325/1-1403250K25I27.png" alt></p>
<center><strong>图 18-7  Modbus 调试精灵</strong></center>

<p>如图，我们的 USB 转 RS485 模块虚拟出的是 COM5，波特率 9600，无校验位，数据位是 8 位，1 位停止位，设备地址假设为 1。</p>
<p>写寄存器的时候，如果我们要把 01 写到一个地址是 0000 的寄存器地址里，点一下“写入”，就会出现发送指令：01 06 00 00 00 01 48 0A。我们来分析一下这帧数据，其中 01 是设备地址，06 是功能码，代表写寄存器这个功能，后边跟 00 00 表示的是要写入的寄存器的地址，00 01 就是要写入的数据，48 0A 就是 CRC 校验码，这是软件自动算出来的。而根据 Modbus协议，当写寄存器的时候，从机成功完成该指令的操作后，会把主机发送的指令直接返回，我们的调试精灵会接收到这样一帧数据：01 06 00 00 00 01 48 0A。</p>
<p>假如我们现在要从寄存器地址 0002 开始读取寄存器，并且读取的数量是 2 个。点一下“读出”，就会出现发送指令：01 03 00 02 00 02 65 CB。其中 01 是设备地址，03 是功能码，代表读寄存器这个功能，00 02 就是读寄存器的起始地址，后一个 00 02 就是要读取 2 个寄存器的数值，65 CB 就是 CRC 校验。而接收到的数据是：01 03 04 00 00 00 00 FA 33。其中 01是设备地址，03 是功能码，04 代表的是后边读到的数据字节数是 4 个，00 00 00 00 分别是地址为 00 02 和 00 03 的寄存器内部的数据，而 FA 33 就是 CRC 校验了。</p>
<p>似乎越来越明朗了，所谓的 Modbus 通信协议，无非就是主机下发了不同的指令，从机根据指令的判断来执行不同的操作而已。由于我们的开发板没有 Modbus 功能码那么多相应的功能，我们在程序中定义了一个数组 regGroup[5]，相当于 5 个寄存器，此外又定义了第 6个寄存器，控制蜂鸣器，通过下发不同的指令我们改变寄存器组的数据或者改变蜂鸣器的开关状态。在 Modbus 协议里寄存器的地址和数值都是 16 位的，即 2 个字节，我们默认高字节是 0x00，低字节就是数组 regGroup 对应的值。其中地址 0x0000 到 0x0004 对应的就是 regGroup数组中的元素，我们写入的同时把数字又显示到 1602 液晶上，而 0x0005 这个地址，写入 0x00，蜂鸣器就不响，写入任何其它数值，蜂鸣器就报警。我们单片机的主要工作也就是解析串口接收的数据执行不同操作。<br>/<strong><strong><strong><strong><strong><strong>***</strong></strong></strong></strong></strong></strong>Lcd1602.c 文件程序源代码<strong><strong><strong><strong><strong><strong><strong>*</strong></strong></strong></strong></strong></strong></strong>/<br>（此处省略，可参考之前章节的代码）<br>/<strong><strong><strong><strong><strong><strong><em>**</em></strong></strong></strong></strong></strong></strong>RS485.c 文件程序源代码<strong><strong><strong><strong><strong><strong><strong>*</strong></strong></strong></strong></strong></strong></strong>/<br>（此处省略，可参考之前章节的代码）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">/****************************CRC16.c 文件程序源代码****************************/</span><br><span class="line">/* CRC16 计算函数，ptr-数据指针，len-数据长度，返回值-计算出的 CRC16 数值 */</span><br><span class="line">unsigned int GetCRC16(unsigned char *ptr, unsigned char len)&#123;</span><br><span class="line">    unsigned int index;</span><br><span class="line">    unsigned char crch = 0xFF; //高 CRC 字节</span><br><span class="line">    unsigned char crcl = 0xFF; //低 CRC 字节</span><br><span class="line">    unsigned char code TabH[] = &#123; //CRC 高位字节值表</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,</span><br><span class="line">        0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,</span><br><span class="line">        0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,</span><br><span class="line">        0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,</span><br><span class="line">        0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,</span><br><span class="line">        0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,</span><br><span class="line">        0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,</span><br><span class="line">        0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,</span><br><span class="line">        0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,</span><br><span class="line">        0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,</span><br><span class="line">        0x80, 0x41, 0x00, 0xC1, 0x81, 0x40</span><br><span class="line">    &#125; ;</span><br><span class="line">    unsigned char code TabL[] = &#123; //CRC 低位字节值表</span><br><span class="line">        0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,</span><br><span class="line">        0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,</span><br><span class="line">        0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,</span><br><span class="line">        0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,</span><br><span class="line">        0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,</span><br><span class="line">        0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,</span><br><span class="line">        0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,</span><br><span class="line">        0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,</span><br><span class="line">        0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,</span><br><span class="line">        0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,</span><br><span class="line">        0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,</span><br><span class="line">        0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,</span><br><span class="line">        0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,</span><br><span class="line">        0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,</span><br><span class="line">        0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,</span><br><span class="line">        0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,</span><br><span class="line">        0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,</span><br><span class="line">        0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,</span><br><span class="line">        0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,</span><br><span class="line">        0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,</span><br><span class="line">        0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,</span><br><span class="line">        0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,</span><br><span class="line">        0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,</span><br><span class="line">        0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,</span><br><span class="line">        0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,</span><br><span class="line">        0x43, 0x83, 0x41, 0x81, 0x80, 0x40</span><br><span class="line">    &#125; ;</span><br><span class="line">   </span><br><span class="line">    while (len--)&#123; //计算指定长度的 CRC</span><br><span class="line">        index = crch ^ *ptr++;</span><br><span class="line">        crch = crcl ^ TabH[index];</span><br><span class="line">        crcl = TabL[index];</span><br><span class="line">    &#125;</span><br><span class="line">    return ((crch&lt;&lt;8) | crcl);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>关于 CRC 校验的算法，如果不是专门学习校验算法本身，大家可以不去研究这个程序的细节，直接使用现成的函数即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br></pre></td><td class="code"><pre><span class="line">/*****************************main.c 文件程序源代码******************************/</span><br><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">sbit BUZZ = P1^6;</span><br><span class="line">bit flagBuzzOn = 0; //蜂鸣器启动标志</span><br><span class="line">unsigned char T0RH = 0; //T0 重载值的高字节</span><br><span class="line">unsigned char T0RL = 0; //T0 重载值的低字节</span><br><span class="line">unsigned char regGroup[5]; //Modbus 寄存器组，地址为 0x00～0x04</span><br><span class="line">void ConfigTimer0(unsigned int ms);</span><br><span class="line">extern void UartDriver();</span><br><span class="line">extern void ConfigUART(unsigned int baud);</span><br><span class="line">extern void UartRxMonitor(unsigned char ms);</span><br><span class="line">extern void UartWrite(unsigned char *buf, unsigned char len);</span><br><span class="line">extern unsigned int GetCRC16(unsigned char *ptr, unsigned char len);</span><br><span class="line">extern void InitLcd1602();</span><br><span class="line">extern void LcdShowStr(unsigned char x, unsigned char y, unsigned char *str);</span><br><span class="line">void main()&#123;</span><br><span class="line">    EA = 1; //开总中断</span><br><span class="line">    ConfigTimer0(1); //配置 T0 定时 1ms</span><br><span class="line">    ConfigUART(9600); //配置波特率为 9600</span><br><span class="line">    InitLcd1602(); //初始化液晶</span><br><span class="line">   </span><br><span class="line">    while (1)&#123;</span><br><span class="line">        UartDriver(); //调用串口驱动</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 串口动作函数，根据接收到的命令帧执行响应的动作</span><br><span class="line">buf-接收到的命令帧指针，len-命令帧长度 */</span><br><span class="line">void UartAction(unsigned char *buf, unsigned char len)&#123;</span><br><span class="line">    unsigned char i;</span><br><span class="line">    unsigned char cnt;</span><br><span class="line">    unsigned char str[4];</span><br><span class="line">    unsigned int crc;</span><br><span class="line">    unsigned char crch, crcl;</span><br><span class="line">    /* 本例中的本机地址设定为 0x01，</span><br><span class="line">    如数据帧中的地址字节与本机地址不符，</span><br><span class="line">    则直接退出，即丢弃本帧数据不做任何处理 */</span><br><span class="line">    if (buf[0] != 0x01)&#123;</span><br><span class="line">        return;</span><br><span class="line">    &#125;</span><br><span class="line">    //地址相符时，再对本帧数据进行校验</span><br><span class="line">    crc = GetCRC16(buf, len-2); //计算 CRC 校验值</span><br><span class="line">    crch = crc &gt;&gt; 8;</span><br><span class="line">    crcl = crc &amp; 0xFF;</span><br><span class="line">    if ((buf[len-2]!=crch) || (buf[len-1]!=crcl))&#123;</span><br><span class="line">        return; //如 CRC 校验不符时直接退出</span><br><span class="line">    &#125;</span><br><span class="line">    //地址和校验字均相符后，解析功能码，执行相关操作</span><br><span class="line">    switch (buf[1])&#123;</span><br><span class="line">        case 0x03: //读取一个或连续的寄存器</span><br><span class="line">            if ((buf[2]==0x00) &amp;&amp; (buf[3]&lt;=0x05))&#123; //只支持 0x0000～0x0005</span><br><span class="line">                if (buf[3] &lt;= 0x04)&#123;</span><br><span class="line">                    i = buf[3]; //提取寄存器地址</span><br><span class="line">                    cnt = buf[5]; //提取待读取的寄存器数量</span><br><span class="line">                    buf[2] = cnt*2; //读取数据的字节数，为寄存器数*2</span><br><span class="line">                    len = 3; //帧前部已有地址、功能码、字节数共 3 个字节</span><br><span class="line">                    while (cnt--)&#123;</span><br><span class="line">                        buf[len++] = 0x00; //寄存器高字节补 0</span><br><span class="line">                        buf[len++] = regGroup[i++]; //寄存器低字节</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;else&#123; //地址 0x05 为蜂鸣器状态</span><br><span class="line">                    buf[2] = 2; //读取数据的字节数</span><br><span class="line">                    buf[3] = 0x00;</span><br><span class="line">                    buf[4] = flagBuzzOn;</span><br><span class="line">                    len = 5;</span><br><span class="line">                &#125;</span><br><span class="line">                break;</span><br><span class="line">            &#125;else&#123; //寄存器地址不被支持时，返回错误码</span><br><span class="line">                buf[1] = 0x83; //功能码最高位置 1</span><br><span class="line">                buf[2] = 0x02; //设置异常码为 02-无效地址</span><br><span class="line">                len = 3;</span><br><span class="line">                break;</span><br><span class="line">            &#125;</span><br><span class="line">       </span><br><span class="line">        case 0x06: //写入单个寄存器</span><br><span class="line">            if ((buf[2]==0x00) &amp;&amp; (buf[3]&lt;=0x05))&#123; //只支持 0x0000～0x0005</span><br><span class="line">               if (buf[3] &lt;= 0x04)&#123;</span><br><span class="line">                    i = buf[3]; //提取寄存器地址</span><br><span class="line">                    regGroup[i] = buf[5]; //保存寄存器数据</span><br><span class="line">                    cnt = regGroup[i] &gt;&gt; 4; //显示到液晶上</span><br><span class="line">                    if (cnt &gt;= 0xA)&#123;</span><br><span class="line">                        str[0] = cnt - 0xA + &apos;A&apos;;</span><br><span class="line">                    &#125;else&#123;</span><br><span class="line">                        str[0] = cnt + &apos;0&apos;;</span><br><span class="line">                    &#125;</span><br><span class="line">                    cnt = regGroup[i] &amp; 0x0F;</span><br><span class="line">                    if (cnt &gt;= 0xA)&#123;</span><br><span class="line">                        str[1] = cnt - 0xA + &apos;A&apos;;</span><br><span class="line">                    &#125;else&#123;</span><br><span class="line">                        str[1] = cnt + &apos;0&apos;;</span><br><span class="line">                    &#125;</span><br><span class="line">                    str[2] = &apos;\0&apos;;</span><br><span class="line">                    LcdShowStr(i*3, 0, str);</span><br><span class="line">                &#125;else&#123; //地址 0x05 为蜂鸣器状态</span><br><span class="line">                    flagBuzzOn = (bit)buf[5]; //寄存器值转为蜂鸣器的开关</span><br><span class="line">                &#125;</span><br><span class="line">                len -= 2; //长度-2 以重新计算 CRC 并返回原帧</span><br><span class="line">                break;</span><br><span class="line">            &#125;else&#123; //寄存器地址不被支持时，返回错误码</span><br><span class="line">                buf[1] = 0x86; //功能码最高位置 1</span><br><span class="line">                buf[2] = 0x02; //设置异常码为 02-无效地址</span><br><span class="line">                len = 3;</span><br><span class="line">                break;</span><br><span class="line">            &#125;</span><br><span class="line">       </span><br><span class="line">        default: //其它不支持的功能码</span><br><span class="line">            buf[1] |= 0x80; //功能码最高位置 1</span><br><span class="line">            buf[2] = 0x01; //设置异常码为 01-无效功能</span><br><span class="line">            len = 3;</span><br><span class="line">            break;</span><br><span class="line">    &#125;</span><br><span class="line">    crc = GetCRC16(buf, len); //计算返回帧的 CRC 校验值</span><br><span class="line">    buf[len++] = crc &gt;&gt; 8; //CRC 高字节</span><br><span class="line">    buf[len++] = crc &amp; 0xFF; //CRC 低字节</span><br><span class="line">    UartWrite(buf, len); //发送返回帧</span><br><span class="line">&#125;</span><br><span class="line">/* 配置并启动 T0，ms-T0 定时时间 */</span><br><span class="line">void ConfigTimer0(unsigned int ms)&#123;</span><br><span class="line">    unsigned long tmp; //临时变量</span><br><span class="line">    tmp = 11059200 / 12; //定时器计数频率</span><br><span class="line">    tmp = (tmp * ms) / 1000; //计算所需的计数值</span><br><span class="line">    tmp = 65536 - tmp; //计算定时器重载值</span><br><span class="line">    tmp = tmp + 33; //补偿中断响应延时造成的误差</span><br><span class="line">    T0RH = (unsigned char)(tmp&gt;&gt;8); //定时器重载值拆分为高低字节</span><br><span class="line">    T0RL = (unsigned char)tmp;</span><br><span class="line">    TMOD &amp;= 0xF0; //清零 T0 的控制位</span><br><span class="line">    TMOD |= 0x01; //配置 T0 为模式 1</span><br><span class="line">    TH0 = T0RH; //加载 T0 重载值</span><br><span class="line">    TL0 = T0RL;</span><br><span class="line">    ET0 = 1; //使能 T0 中断</span><br><span class="line">    TR0 = 1; //启动 T0</span><br><span class="line">&#125;</span><br><span class="line">/* T0 中断服务函数，执行串口接收监控和蜂鸣器驱动 */</span><br><span class="line">void InterruptTimer0() interrupt 1&#123;</span><br><span class="line">    TH0 = T0RH; //重新加载重载值</span><br><span class="line">    TL0 = T0RL;</span><br><span class="line">    if (flagBuzzOn)&#123; //执行蜂鸣器鸣叫或关闭</span><br><span class="line">        BUZZ = ~BUZZ;</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        BUZZ = 1;</span><br><span class="line">    &#125;</span><br><span class="line">    UartRxMonitor(1); //串口接收监控</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>大家可以看到负责解析协议的 UartAction 函数很长，因为协议解析本来就是一件很繁琐的事情。我们的例程仅解析执行了两个功能命令，就已经有近百行程序了，如果你需要解析更多的功能命令的话，那么建议把每个功能都做一个函数，然后在相应的 case 分支里调用即可，这样就不会使单个函数过于庞大而难以维护。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/limh/tags/教程/" rel="tag"># 教程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/limh/2014/12/01/mcu118/" rel="next" title="18.2、Modbus通信协议介绍">
                <i class="fa fa-chevron-left"></i> 18.2、Modbus通信协议介绍
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/limh/2015/01/01/c01/" rel="prev" title="C简介">
                C简介 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/limh/images/avatar.jpg" alt="土逗牛肉">
            
              <p class="site-author-name" itemprop="name">土逗牛肉</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/limh/archives/">
              
                  <span class="site-state-item-count">255</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/limh/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/limh/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/limhGeek" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1591054297@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/f73b243e7cc9" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-user-circle-o"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土逗牛肉</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
	var str = GetUrlParam('height');
    if (str === '0'){
		document.getElementById('header').style.display = 'none';
		document.getElementById('comments').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
		document.getElementsByClassName('post-footer').item(0).style.display = 'none'
	}
	
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                 arr = arrPara[i].split("=");

                if (arr != null && arr[0] === paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }
</script>









  












  
  
    <script type="text/javascript" src="/limh/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/limh/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/limh/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/limh/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/limh/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/limh/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
